package com.zsc.projectmanagementapi.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.projectmanagementapi.dao.UserMapper;
import com.zsc.projectmanagementapi.pojo.Do.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * 定义shiro框架：用户域
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {
    //Shiro框架的两个核心模块：认证和授权

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 权限认证登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取token
        String token = (String) authenticationToken.getCredentials();
        //解密，获取userId
        String username = JWTUtil.getUsername(token);
        log.info("{}账号验证", username);

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        try {
            if (user != null && JWTUtil.verify(token)){
                return new SimpleAuthenticationInfo(token,token,this.getName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 授权处理：保存用户角色
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String token = principalCollection.toString();
//        System.out.println("->>>>>>>" + token);
        String authorityId = JWTUtil.getUserAuthorityId(token);;
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> role = new HashSet<>();
        //记录当前登录用户的角色：0普通用户、1管理员
        // role.add(user.getUserAuthority()+"");
        role.add("user");
        authorizationInfo.setRoles(role);
        return authorizationInfo;
    }



}
